package cn.edu.scujcc;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CompanyService {
	@Autowired
	private CompanyRepository repo;
	
	public Company createCompany(Company c) {
		Company result = null;
		result = repo.save(c);
		return result;
	}

	public Company updateCompany(Company c) {
		Company result = null;
		result = getCompany(c.getId());
		if (result != null) {
			if (c.getName() != null) {
				result.setName(c.getName());
			}
			if (c.getTelnum() != null) {
				result.setTelnum(c.getTelnum());
			}
			if (c.getInformation() != null) {
				result.setInformation(c.getInformation());
			}
			if (c.getAnnounce() != null) {
				result.setAnnounce(c.getAnnounce());
			}
			result = repo.save(result);
		}
		
		return result;
	}

	public List<Company> getAllCompany() {
		List<Company> result = null;
		result = repo.findAll();
		return result;
	}
	
	public Company getCompany(String id) {
		Company result = null;
		Optional<Company> op = repo.findById(id);
		if (op.isPresent()) {
			result = op.get();
		}
		return result;
	}
	
	public boolean deleteCompany(String id) {
		boolean result = true;
		try {
			repo.deleteById(id);
		} catch (Exception c) {
			result = false;
		}
		return result;
	}
	
	public List<Company> searchCompany(String name){
		List<Company> result = null;
		result = repo.findByName(name);
		return result;
	}

	
}
